<template>
  <div style="width: 100%; height: 100%;min-width: 422px" ref="deviceMonitor">
    <div class="until_title">设备监控</div>

    <div class="device-top"  ref="deviceTop">
      <div class="left">
        <p class="device-Number-c">{{deviceData.towercraneOnlineCount}}</p>
        <p class="device-t">在线塔吊</p>
      </div>
      <div class="left">
        <p class="device-Number-w">{{deviceData.towercraneOfflineCount}}</p>
        <p class="device-t">离线塔吊</p>
      </div>
      <div class="device-line left"></div>
      <div class="left">
        <p class="device-Number-c">{{deviceData.elevatorOnlineCount}}</p>
        <p class="device-t">在线升降机</p>
      </div>
      <div class="left">
        <p class="device-Number-w">{{deviceData.elevatorOfflineCount}}</p>
        <p class="device-t">离线升降机</p>
      </div>
    </div>

    <div ref="deviceMonitorEchart" class="left" style="width: 50%" :style="{height: `${height}px`}"></div>
    <div ref="deviceMonitorElvEchart" class="right" style="width: 50%" :style="{height: `${height}px`}"></div>

    <div class="clear device-status-div">
      <div class="left clear device-status">
       <div class="left device-office"></div>
       <div class="left">离线</div>
      </div>
      <div class="left clear device-status">
        <div class="left device-waring"></div>
        <div class="left">预警</div>
      </div>
      <div class="left clear device-status">
        <div class="left device-error"></div>
        <div class="left">报警</div>
      </div>
    </div>

  </div>
</template>

<script>
  import elevator from './elevator.js'
  import { mapGetters } from 'vuex'
  export default {
    name: 'deviceMonitor',
    mixins: [elevator],
    data () {
      return {
        towerInterval: null,
        deviceData: {
          towercraneOnlineCount: 0,
          towercraneOfflineCount: 0,
          towercraneLiveList: [],
          elevatorLiveList: [],
          elevatorOfflineCount: 0,
          elevatorOnlineCount: 0
        },
        towerMap: new Map(),
        towerIndex: 0,
        towerData: [],
        towerDataColor: {
          0: {name: '离线', color: '#1e618c'},
          1: {name: '在线', color: '#1fadff'},
          2: {name: '预警', color: '#ffc600'},
          3: {name: '报警', color: '#fb6161'}
        },
        height: 0,
        resizeTimer: null,
        deviceOption: {
          tooltip: {
            show: true,
            backgroundColor: 'none',
            triggerOn: 'none'
          },
          legend: {
            orient: 'vertical',
            x: 'bottom',
            data: ['离线', '预警', '报警']
          },
          series: [
            {
              name: '塔吊',
              id: 'tower',
              type: 'pie',
              radius: ['65%', '88%'],
              center: ['100%', '50%'],
              silent: false,
              hoverAnimation: false,
              legendHoverLink: false,
              label: {
                show: false
              },
              data: []
            },
            {
              name: '背景',
              type: 'pie',
              radius: ['65%', '58%'],
              center: ['100%', '50%'],
              silent: true,
              hoverAnimation: false,
              legendHoverLink: false,
              label: {
                show: false
              },
              labelLine: {
                show: false
              },
              data: [
                {name: '1', value: 0.46, itemStyle: {color: '#0f4061'}},
                {name: '2', value: 0.54, itemStyle: {color: 'transparent'}}
              ]
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters({
        currentUser: 'currentUser',
        incomingProjectBroadcastNode: 'incomingProjectBroadcastNode'
      })
    },
    watch: {
      currentUser () {
        if (this.currentUser.mid && this.$route.name === 'projectVideo') {
          this.initDeviceMonitor()
        }
      },
      incomingProjectBroadcastNode (item) {
        if (this.$route.name === 'projectVideo') {
          this.incomingProjectNode(item)
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        const rectProson = this.$refs.deviceMonitor.getBoundingClientRect()
        const rectTop = this.$refs.deviceTop.getBoundingClientRect()
        this.height = rectProson.height - rectTop.height - 42
        this.initDeviceMonitor()
        if (!this.towerInterval) {
          this.towerInterval = setInterval(() => {
            if (this.$route.name === 'projectVideo') {
              this.initDeviceMonitor()
            }
          }, 1000 * 60 * this.$pollingTime)
        }
      })
    },
    activated () {
      this.initDeviceMonitor()
    },
    methods: {
      incomingProjectNode (obj) {
        switch (obj.type) {
          // 塔机开机
          case 1:
            this.initDeviceMonitor()
            break
          // 塔吊关机
          case 2:
            this.initDeviceMonitor()
            break
          // 升降机开机
          case 3:
            this.initDeviceMonitor()
            break
          // 升降机关机
          case 4:
            this.initDeviceMonitor()
            break
          // 塔机吊次
          case 5:
            this.initDeviceMonitor()
            break
          // 升降机运次
          case 6:
            this.initDeviceMonitor()
            break
          // 塔机预警
          case 13:
            this.initDeviceMonitor()
            break
          // 塔机报警
          case 14:
            this.initDeviceMonitor()
            break
          // 升降机预警
          case 15:
            this.initDeviceMonitor()
            break
          // 升降机报警
          case 16:
            this.initDeviceMonitor()
            break
          // 报警消失
          case 21:
            this.initDeviceMonitor()
            break
          // 报警消失
          case 22:
            this.initDeviceMonitor()
            break
          // 报警消失
          case 23:
            this.initDeviceMonitor()
            break
        }
        /*
        * status 消息状态
        * 1 普通消息
        * 2 预警消息
        * 3 报警消息
        * 4 取消报警
        * 5 视屏监控报警 滚动 不固定
        * 6 视屏监控预警 滚动 不固定
        * */
      },
      initDeviceMonitor () {
        this.findMonitor().then(() => {
          this.initTower()
          this.initElevator()
        })
      },
      findMonitor () {
        return new Promise(resolve => {
          const data = {
            'stageId': this.currentUser.stageId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.videoServer}/api/screen/getDeviceMonitor`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            this.deviceData = res.data.data
            resolve()
          })
        })
      },
      initTower () {
        if (this.personMonitorEchart) {
          this.$echarts.dispose(this.$refs.deviceMonitorEchart)
          window.clearInterval(this.towerInterval)
          this.towerInterval = null
        }
        this.towerData = []
        const transparentLength = this.deviceData.towercraneLiveList.length * 0.54
        if (transparentLength > 0) {
          const dataLength = this.deviceData.towercraneLiveList.length - transparentLength
          const startAngle = (dataLength) / 2 / (dataLength + transparentLength) * 360 + 180
          this.deviceData.towercraneLiveList.forEach((item) => {
            let deviceId = Number.parseInt(item.deviceId)
            this.towerMap.set(deviceId, item)
            this.towerData.push({
              name: `${item.driverName}-${deviceId}`,
              value: (dataLength / this.deviceData.towercraneLiveList.length).toFixed(2),
              labelLine: {
                show: false,
                length: 10,
                length2: 60
              },
              itemStyle: {
                color: this.towerDataColor[item.status].color,
                borderColor: '#0f4061',
                borderWidth: 1
              },
              tooltip: {
                position: (point, params) => {
                  let half = this.towerMap.size / 2
                  let top = point[1]
                  if (half > params.dataIndex) {
                    top -= 65
                  } else {
                    top -= 25
                  }
                  return {left: 0, top: top}
                },
                formatter: (params) => {
                  if (params.name) {
                    const name = params.name.split('-')
                    const tower = this.towerMap.get(Number.parseInt(name[1]))
                    const statusNum = Number.parseInt(tower.status)
                    const drive = tower.driverName || ''
                    const status = this.towerDataColor[statusNum].name
                    let eventType = '开机'
                    let eventTime = tower.openTime || ''
                    let color = ''
                    if (statusNum === 2 || statusNum === 3) {
                      color = this.towerDataColor[statusNum].color
                      eventType = '事件'
                      eventTime = tower.event
                    } else if (statusNum === 0) {
                      eventType = '开机'
                      eventTime = '未开机'
                    }
                    return `<p style="font-size: 16px; font-weight: bold; color: ${color};">${tower.deviceName}</p>
                    <p style="font-size: 14px; margin-top: 10px;"><span style="color: #a8c5ed; margin: 0 10px 0 0;">状态:</span><span style="color: ${color}">${status}</span></p>
                    <p style="font-size: 14px; margin-top: 5px;"><span style="color: #a8c5ed; margin: 0 10px 0 0;">${eventType}:</span><span >${eventTime}</span></p>
                    <p style="font-size: 14px; margin-top: 5px;"><span style="color: #a8c5ed; margin: 0 10px 0 0;">司机:</span><span >${drive}</span></p>`
                  }
                }
              }
            })
          })
          this.towerData.push({
            name: 'transparent',
            value: transparentLength,
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            itemStyle: {
              color: 'transparent'
            },
            tooltip: {
              show: false
            },
            emphasis: {
              label: {
                show: false
              }
            }
          })
          this.deviceOption.series[0].data = this.towerData
          this.deviceOption.series[0].startAngle = startAngle
          this.deviceOption.series[1].startAngle = startAngle
          this.personMonitorEchart = this.$echarts.init(this.$refs.deviceMonitorEchart)
          this.personMonitorEchart.setOption(this.deviceOption)
          this.setHoverTower()
          this.initInterval()
          this.personMonitorEchart.on('mouseover', (params) => {
            if (params.name === 'transparent') {
              return
            }
            this.towerIndex = params.dataIndex
            this.setHoverTower()
            window.clearInterval(this.towerInterval)
            this.towerInterval = null
          })
          this.personMonitorEchart.on('mouseout', (params) => {
            if (params.name === 'transparent') {
              return
            }
            this.towerIndex = params.dataIndex + 1
            this.initInterval()
          })
        }
      },
      initInterval () {
        if (!this.towerInterval) {
          this.towerInterval = setInterval(() => {
            if (this.towerIndex === this.deviceData.towercraneLiveList.length) {
              this.towerIndex = 0
            }
            this.setHoverTower()
            this.towerIndex++
          }, 1000 * 5)
        }
      },
      setHoverTower () {
        this.towerData.forEach((item, i) => {
          if (item.name !== 'transparent') {
            item.labelLine.show = false
            if (this.towerIndex === i) {
              item.labelLine.show = true
            }
          }
        })
        this.personMonitorEchart.setOption({
          series: [
            {
              name: '塔吊',
              data: this.towerData
            }
          ]
        })
        this.personMonitorEchart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: this.towerIndex
        })
      }
    }
  }
</script>

<style scoped lang='scss'>
  .device-top{
    margin-top: -8px;
    padding: 5px;
    box-sizing: border-box;
    width: 100%;
    height: 60px;
    box-shadow: 0 0 6px 1px rgba(9, 94, 114, 0.85) inset;
    background: rgba(26, 103, 151, 0.1);
    >div {
      text-align: center;
      width: 24%;
      &:nth-child(3){
              width: 2px;
            }
    }
    .device-Number-c{
      color: #00e7ff;
      font-size: 20px;
      font-weight: bold;
      text-align: center;
    }
    .device-Number-w{
      color: #fff;
      font-size: 20px;
      font-weight: bold;
      text-align: center;
    }
    .device-t{
      margin-top: 6px;
    }
    .device-line{
      width: 1px;
      height: 35px;
      background-image: url("/static/images/line-duan.png");
    }
  }
  .device-status-div{
    width: 203px;
    height: 12px;
    margin: 0 auto;
    .device-status{
      line-height: 12px;
      height: 12px;
      margin-right: 20px;
      .device-office{
        margin-right: 7px;
        background: #1e618c;
        width: 12px;
        height: 12px;
      }
      .device-waring{
        margin-right: 7px;
        background: #ffc600;
        width: 12px;
        height: 12px;
      }
      .device-error{
        margin-right: 7px;
        background: #f76160;
        width: 12px;
        height: 12px;
      }
    }
  }
</style>
